package control

import (
	"fmt"
	"github.com/labstack/echo/v4"
	"github.com/zxysilent/utils"
	"time"
	"turingApi/conf"
	"turingApi/model"
)

func VideoLogHandler(c echo.Context) error {
	jcc, err := LoadUser(c)
	if err != nil {
		conf.Logger.Error(fmt.Sprintf("打点异常：%v", err))
		return c.JSON(utils.Fail("加载用户数据失败", err))
	}

	user, has := model.UserGetByOpenid(jcc.OpenId)
	if has {

		al := model.AdLogs{UserId: user.Id, Created: time.Now()}
		if err := model.AdAdd(&al); err != nil {
			conf.Logger.Error(fmt.Sprintf("添加打点日志异常：%v", err))
			return c.JSON(utils.Fail("添加打点日志异常", err))
		}
		return c.JSON(utils.Succ("succ", user))
	}
	return c.JSON(utils.Fail("用户不存在"))
}

func VideoRewardHandler(c echo.Context) error {
	jcc, err := LoadUser(c)
	if err != nil {
		conf.Logger.Error(fmt.Sprintf("奖励异常：%v", err))
		return c.JSON(utils.Fail("加载用户数据失败", err))
	}

	user, has := model.UserGetByOpenid(jcc.OpenId)
	if has {
		ads, err := model.GetTodayAds(user.Id)
		if err != nil {
			conf.Logger.Info("获取广告日志失败")
			return c.JSON(utils.Fail("获取广告日志失败"))
		}
		if len(ads) >= 5 {
			conf.Logger.Info("今日观看已达5次")
			return c.JSON(utils.Fail("今日观看已达5次"))
		}
		ad, has := model.GetAdLog(user.Id)
		if !has {
			conf.Logger.Info("没有广告观看开始记录")
			return c.JSON(utils.Fail("广告未看完"))
		}
		ad.Status = true
		ad.Updated = time.Now()
		if err := model.AdEdit(ad, "status,updated"); err != nil {
			conf.Logger.Error(fmt.Sprintf("更新日志状态失败：%v", err))
			return c.JSON(utils.Fail("更新日志状态失败", err))
		}
		user.Balance += 2
		if err := model.UserEdit(user, "balance"); err != nil {
			conf.Logger.Error(fmt.Sprintf("更新用户数据失败：%v", err))
			return c.JSON(utils.Fail("更新用户数据失败", err))
		}
		conf.Logger.Info(fmt.Sprintf("看广告成功并加2积分"))
		return c.JSON(utils.Succ("succ", user))
	}
	return c.JSON(utils.Fail("用户不存在"))
}
